import "./vendor";

const { regeneratorRuntime, util, api, _, moment } = global
App({
  globalData: {
    token: null,
    userInfo: null,
    dicts: {},
    share: false,
    openId: null,
    coordinate: null,
    fileServer: 'https://jquee-dev.oss-cn-beijing.aliyuncs.com/',
    params: null,
    back: null
  },
  onLaunch(options) {
    // 判断是否由分享进入小程序
    this.globalData.share = options.scene == 1007 || options.scene == 1008
  },
  async updateGlobal() {
    let userInfo = await api.system.getUserInfo(this.globalData.userInfo.id)
    this.globalData.userInfo = userInfo
  },
  /**
   *  登录检查
   * @returns
   */
  async checkLoginStatus() {
    const token = util.session('token')
    if (!token) {
      // 目前通过手机号登录，不需要微信认证
      this.toLogin()
    } else {
      this.globalData.token = token
      // let ret = await api.appoint.judgeUser(token)
    }
  },
  // 未登录，进行登录
  toLogin() {
    let url = util.getCurrentPageUrlWithArgs()
    url = encodeURIComponent(url)
    wx.redirectTo({
      url: "/pages/authorization/login?url=" + url
    })
    // wx.switchTab({
    //   url: '/pages/own/index'
    // });
  },
  // 未授权，进入授权
  toAuthorization() {
    let url = util.getCurrentPageUrlWithArgs()
    url = encodeURIComponent(url)
    wx.redirectTo({
      url: "/pages/authorization/index?url=" + url
    })
  },
  async getCoordinate() {
    let that = this
    let { coordinate } = this.globalData
    if (!coordinate || !coordinate.latitude || !coordinate.longitude) {
      try {
        coordinate = await api.wxGetLocation({ type: 'wgs84' })
      } catch (error) { }
      this.globalData.coordinate = coordinate
    }

    return coordinate
  },
  dictFormatter(value, dictName) {
    let result = this.globalData.dicts[dictName];
    if (result) {
      if (_.isArray(value)) {
        let names = [];
        for (let item of value) {
          let status = result.find(x => x.code === item);
          if (status) {
            names.push(status.value);
          }
        }
        return names;
      } else {
        let status = result.find(x => x.code === value);
        if (status) {
          return status.value;
        }
      }
    }
    return "";
  },
  /**
   *  获取图片文件的完整路径
   *
   * @param {String} url 文件地址
   * @param {number} [w=300] 图片类型的文件，宽度；默认300
   * @param {number} [h=200] 图片类型的文件，高度；默认200
   * @returns
   */
  getImgUrl: function (url, w = 750, h = 420) {
    if (url === null || url === undefined || url === "") return "";
    else if (url.indexOf("http") === 0) return url
    else if (url.indexOf("https") === 0) return url

    return (
      this.globalData.fileServer +
      url +
      "?x-oss-process=image/resize,w_" +
      w +
      ",h_" +
      h
    );
  },
  /**
   *  获取文件的完整路径
   *
   * @param {String} url 文件地址
   * @returns
   */
  getFileUrl: function (url) {
    if (url === null || url === undefined || url === "") return "";
    else if (url.indexOf("http") === 0) return url;
    return this.globalData.fileServer + url;
  },
  /**
   * 处理富文本里的图片宽度自适应
   * 1.去掉img标签里的style、width、height属性
   * 2.img标签添加style属性：max-width:100%;height:auto
   * 3.修改所有style里的width属性为max-width:100%
   * 4.去掉<br/>标签
   * @param html
   * @returns {void|string|*}
   */
  formatRichText: function (html) {
    if (!html || html === "") return;
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match
        .replace(/style="[^"]+"/gi, "")
        .replace(/style='[^']+'/gi, "");
      match = match
        .replace(/width="[^"]+"/gi, "")
        .replace(/width='[^']+'/gi, "");
      match = match
        .replace(/height="[^"]+"/gi, "")
        .replace(/height='[^']+'/gi, "");
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (
      match,
      capture
    ) {
      match = match
        .replace(/width:[^;]+;/gi, "max-width:100%;")
        .replace(/width:[^;]+;/gi, "max-width:100%;");
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, "");
    newContent = newContent.replace(
      /\<img/gi,
      '<img style="max-width:100%;height:auto;display:block;margin-top:10px;margin-bottom:10px;"'
    );
    return newContent;
  }
});
